import {getNotifyCount} from "../../api";
import {message} from "../../common/util";

const state = {//数据
  notify:{}
}

const getters = {//获取数据
  /*getNotify: function (state) {
    return state.notify
  }*/
  getNotify: state => {//es6箭头函数写法
    state.notify.allNotice = state.notify.callNotice + state.notify.presentNotice + state.notify.cardNotice + state.notify.keepNotice
    return state.notify
  },
}

const mutations = {//对本地无需ajax的更改，使用mutations
  updateNotify(state,changed){
    state.notify = changed
    state.notify.allNotice = state.notify.callNotice + state.notify.presentNotice + state.notify.cardNotice + state.notify.keepNotice
  },
  addNotifyItem(state,changed){
    switch (changed.type) {
      case 'callNotice':state.notify.callNotice += changed.count;break
      case 'presentNotice':state.notify.presentNotice += changed.count;break
      case 'cardNotice':state.notify.cardNotice += changed.count;break
      case 'keepNotice':state.notify.keepNotice += changed.count;break
      default:break
    }
    state.notify.allNotice = state.notify.callNotice + state.notify.presentNotice + state.notify.cardNotice + state.notify.keepNotice
  },
  updateNotifyItem(state,changed){
    switch (changed.type) {
      case 'callNotice':state.notify.callNotice = changed.count;break
      case 'presentNotice':state.notify.presentNotice = changed.count;break
      case 'cardNotice':state.notify.cardNotice = changed.count;break
      case 'keepNotice':state.notify.keepNotice = changed.count;break
      default:break
    }
    state.notify.allNotice = state.notify.callNotice + state.notify.presentNotice + state.notify.cardNotice + state.notify.keepNotice
  },
  clearNotify(state,changed){
    state.notify = {}
  }
}

const actions = {//action好处适合异步操作，action先执与后端交互，mutations后执行
  fetchNotify({commit,state},params){
    getNotifyCount(this.getters.getAuthorityNotice).then((res)=>{
      if(res.status == 'success') {
        commit('updateNotify', res.data)
      }else if(res.status == 'error'){
        console.log('getNotifyCount error info:',res.msg)
        message({message:res.msg,type: 'error'})
      }
      if(params.callback != undefined)params.callback(res.status)
    }).catch((err)=>{console.log('getNotifyCount catch info:',err)})
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
